package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.util.BeanUtil;

import cn.imvc.app.entities.RefRelation;
import cn.imvc.app.repositories.RefRelationRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
import net.sf.ehcache.hibernate.management.impl.BeanUtils;

@Service
public class RefRelationModelImpl implements RefRelationModel {
	@Autowired
	private RefRelationRepository refRelationRepository;
	public void save(RefRelation refRelation) {
		refRelationRepository.save(refRelation);
	}
	/**
	 * 根据  被引用表（refTable）排序
	 */
	public Page<RefRelation> findAll(ViewRequest viewRequest) {
		if(viewRequest == null){
			viewRequest = new ViewRequest();
		}
		viewRequest.getSort().put("refTable", "DESC");
		return refRelationRepository.findAll(viewRequest);
	}
	public RefRelation getOne(int id) {
		return refRelationRepository.getOne(id);
	}
	public void update(int id,RefRelation refRelation) {
		refRelation.setId(id);
		refRelationRepository.saveAndFlush(refRelation);
	}
	public void delete(int id) {
		refRelationRepository.delete(id);
	}
	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			delete(id);
		}
	}
	public String deleteDateCheck(String refTable, String refField, int id) {
		String allSql = "select * from ref_relation where refTable = '" + refTable + "'";
		List<RefRelation> refRelationList = refRelationRepository.findAllSql(allSql,RefRelation.class);
		if(refRelationList.isEmpty()){
		return "";
		}else{
			for (RefRelation refRelation : refRelationList) {
				//第一个字母
				String sql = "select * from " + refRelation.getDataTable() + "　where " + refRelation.getDataField() + " = " + id;
				List<Object[]> objList = refRelationRepository.findAllSql(sql);
				if(!objList.isEmpty()) 
					return refRelation.getDelMsg();
				
			}
		}
		return "";
	}
}
